import React, { memo, useEffect, useRef, useState } from 'react'
import { ToolBarViewStyle } from './style'
import { Button, Dropdown, Space } from 'antd'
import { DownOutlined } from '@ant-design/icons'
import type { IProps, IButton } from './type'

const ToolBarView = memo((props: IProps) => {
	const { align = 'right', toolbar } = props

	const boxRef = useRef<HTMLDivElement>(null) // 容器
	const boxWidth = useRef<number>(0) // 容器的宽度
	const btnsNum = useRef<number>(0) // 可展示的按钮个数
	const dropNum = useRef<number>(0) // 下拉菜单个数

	const [tools, setTools] = useState<any>([]) // 按钮dom
	const [drops, setDrops] = useState<any>([]) // 下拉按钮dom

	useEffect(() => {
		if (boxRef.current) {
			// 记录容器宽度
			boxWidth.current = boxRef.current.clientWidth

			let btnsNumWidth = 8
			for (let i = 0, k = boxRef.current.children.length; i < k; i++) {
				// 子节点宽度依次累加
				btnsNumWidth += boxRef.current.children[i].clientWidth + 8
				if (btnsNumWidth > boxWidth.current) {
					btnsNum.current = i
					dropNum.current = k - i - 1
					break
				}
			}
			// 如果btnsNum和dropNum不为0，则子节点宽度超过容器，执行重新渲染方法
			if (btnsNum.current !== 0) renderView()
		}
	}, [])

	// 重新渲染工具栏
	const renderView = () => {
		const toolsDoms = [] // 外部按钮
		const dropsDoms = [] // 转为下拉菜单的按钮
		if (toolbar) {
			// 添加为button
			for (let i = 0; i < btnsNum.current - 1; i++) {
				if (React.isValidElement(toolbar[i])) {
					toolsDoms.push(toolbar[i])
				} else {
					toolsDoms.push(
						<Button key={i} {...(toolbar[i] as IButton)}>
							{(toolbar[i] as IButton).label}
						</Button>
					)
				}
			}
			// 添加为下拉菜单
			if (btnsNum.current > 0) {
				for (let i = btnsNum.current - 1, k = toolbar.length; i < k; i++) {
					dropsDoms.push({
						key: i,
						label: React.isValidElement(toolbar[i]) ? (
							toolbar[i]
						) : (
							<div onClick={(toolbar[i] as IButton).onClick}>{(toolbar[i] as IButton).label}</div>
						)
					})
				}
			}
		}
		setTools(toolsDoms)
		setDrops(dropsDoms)
	}

	return (
		<ToolBarViewStyle align={align}>
			<div className="space" ref={boxRef}>
				{tools.length
					? tools
					: toolbar?.map((item, index) => {
							return React.isValidElement(item) ? (
								item
							) : (
								<Button
									key={index}
									type={(item as IButton).type}
									onClick={(item as IButton).onClick}
								>
									{(item as IButton).label}
								</Button>
							)
					  })}
				{drops.length ? (
					<Dropdown menu={{ items: drops }}>
						<Button type="primary" ghost>
							<Space>
								更多
								<DownOutlined />
							</Space>
						</Button>
					</Dropdown>
				) : null}
			</div>
		</ToolBarViewStyle>
	)
})

export default ToolBarView
